/**
 * Created by cb on 15/3/31.
 */
$(function () {
    $(".search-input").dblclick(function(event){
    	event = event || window.event;
    	return false;
    })
    .autocomplete(base+'/searchDown.jhtml', {
        max: 15,
        minChars: 1,
        matchSubset: false,
        matchContains: true,
        autoFill: false,
        scroll: false,
        delay: 400,
        cacheLength: 50,
        selectFirst: false,
        width:428,
        dataType: "json",
        parse: function (data) {
            var rows = [];
            var d = data;
            for (var i = 0; i < d.length; i++) {
                rows[i] = {
                    data: d[i],
                    value: d[i].name,//选中的实际数据
                    result: d[i].name
                };
            }
            return rows;
        },
        formatItem: function (row, i, max) {
            var s =  "<a class='ac_name' href='javascript:;'>" + row.name;
            if (typeof row.pyName != 'undefined' && row.pyName.length) {
                s += "("+row.pyName+")";
            }
            s += "</a>";
            return s;
        },
        formatMatch: function (row, i, max) {
            return row.name;
        },
        formatResult: function (row) {
            return row.name;
        }
    }).result(function(event, data) {
        writeHistory($(this).val());
        searchButtonClick($(this).val());
    }).keydown(function(event, data) {
    	event = event || window.event;
    	if(event.keyCode == 13){
            var val = $(this).val().replace(/\//g,' ');
            $(this).val(val);
            //写入历史记录
            writeHistory(val);
    		$(this).next().trigger('click');
        }
    });

    //监听滚动条，隐藏搜索下拉框
    $(window).scroll(function(){
        $('.ac_results').attr("style", "position: absolute; width: 428px; top: 85px; left: 651.5px; display: none;");
    });

});

function createSearchUrl(val) {
    return base + "/search/"+ encodeURIComponent(val.replace(new RegExp(/\//g), ' ')) +".jhtml"
}

function searchButtonClick(input){
    location.href = createSearchUrl(input);
}

//把数据写入历史记录
function writeHistory(name)
{
    searchHistoryManage().add({name:name});
}
/**
 * 搜索历史记录的管理
 * 依赖于 module.js 下的 oStroge 模块
 */
